package org.doubango.FrCall.Utils;

import java.util.ArrayList;
import java.util.List;

import org.doubango.FrCall.Main;
import org.doubango.FrCall.Screens.BaseScreen;
import org.doubango.FrCall.model.SystemMessage;
import org.doubango.ngn.utils.NgnDataBaseHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SystemMessageManager extends NgnDataBaseHelper {

	private final static String DATABASE_NAME = "recentDB";
	private final static int DATABASE_VERSION = 1;
	private final static String TABLE_NAME = TABLE_SYSTEM_MESSAGE_NAME;
	public static boolean exit = false;
	private static List<SystemMessage> tempList;
	public SystemMessageManager(Context context) {
		super(context, DATABASE_NAME, DATABASE_VERSION, TABLE_ST);
		// TODO Auto-generated constructor stub
	}
	public static Thread checkMessage = new Thread(new Runnable() {
		
		@Override
		public void run() {
			while(!exit)
			{
				if(BaseScreen.sysDB==null)
					continue;
				if(tempList==null || !tempList.equals(Main.mNewMessageList))
				{
					tempList = Main.mNewMessageList;
					for (SystemMessage message : tempList) {
						BaseScreen.sysDB.insert(message);
						Main.sMsgCount++;
					}
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	});

	public long insert(SystemMessage message) {
		if (checkExist(message)) {
			return this.update(message);
		}
		SQLiteDatabase db = this.mDataBaseOpenHelper.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(FIELD_USER_ID, message.getUserId());
		cv.put(FIELD_TO_ID, message.getToID());
		cv.put(FIELD_FROM_ID, message.getFromID());
		cv.put(FIELD_SYSTEM_MESSAGE, message.getMessage());
		cv.put(FIELD_IS_NEW, message.isNew());
		long time = System.currentTimeMillis();
		cv.put(FIELD_TIME, time);
		long row = db.insert(TABLE_NAME, null, cv);
		Log.v("系统消息存储", "存上了。。。。。。。row="+row);
		return row;
	}

	public long delete(String userId,String fromId) {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getWritableDatabase();
		String where = FIELD_USER_ID + "=? AND "+FIELD_FROM_ID+"=?";
		String[] whereValue = { userId,fromId };
		return db.delete(TABLE_NAME, where, whereValue);
	}

	public long update(SystemMessage message) {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getWritableDatabase();
		String where = FIELD_USER_ID + "=?";
		String[] whereValue = { message.getUserId() };
		ContentValues cv = new ContentValues();
		cv.put(FIELD_USER_ID, message.getUserId());
		cv.put(FIELD_TO_ID, message.getToID());
		cv.put(FIELD_FROM_ID, message.getFromID());
		cv.put(FIELD_SYSTEM_MESSAGE, message.getMessage());
		cv.put(FIELD_IS_NEW, message.isNew());
		long time = System.currentTimeMillis();
		cv.put(FIELD_TIME, time);
		return db.update(TABLE_NAME, cv, where, whereValue);
	}

	public Cursor select() {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null,
				FIELD_TIME + " desc");
		return cursor;
	}

	public String getCountStr(String UserID) {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getReadableDatabase();
		;
		int newMsg = 0;
		int totalMsg = 0;
		Cursor cur = db
				.query(TABLE_NAME, null, FIELD_USER_ID + "=?",
						new String[] { UserID }, null, null, " " + FIELD_TIME
								+ " desc");
		cur.moveToFirst();
		totalMsg = cur.getCount();
		while (!cur.isAfterLast() && cur.getCount() > 0) {
			boolean isNew = cur.getString(cur.getColumnIndex(FIELD_IS_NEW)) != null;
			if (isNew)
				newMsg++;
			cur.moveToNext();
		};
		cur.close();
		db.close();
		String count = "[" + newMsg + "/" + totalMsg + "]";
		return count;
	}

	public List<SystemMessage> getUserList(String UserId) {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getReadableDatabase();
		;
		List<SystemMessage> messagelist = new ArrayList<SystemMessage>();
		Cursor cur = db
				.query(TABLE_NAME, null, FIELD_USER_ID + "=?",
						new String[] { UserId }, null, null, " " + FIELD_TIME
								+ " desc");
		cur.moveToFirst();
		while (!cur.isAfterLast() && cur.getCount() > 0) {
			String userId = cur.getString(cur.getColumnIndex(FIELD_USER_ID));
			String fromID = cur.getString(cur.getColumnIndex(FIELD_FROM_ID));
			String toID = cur.getString(cur.getColumnIndex(FIELD_TO_ID));
			String sysMessage = cur.getString(cur
					.getColumnIndex(FIELD_SYSTEM_MESSAGE));
			boolean isNew = cur.getString(cur.getColumnIndex(FIELD_IS_NEW)) != null;
			SystemMessage message = new SystemMessage(userId, fromID, toID,
					sysMessage, isNew);
			messagelist.add(message);
			cur.moveToNext();
		}
		;
		cur.close();
		db.close();
		return messagelist;
	}

	public SystemMessage getUserByUserID(SystemMessage requestMessage) {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getReadableDatabase();
		;
		Cursor cur = db.query(TABLE_NAME, null, FIELD_USER_ID + "=?",
				new String[] { requestMessage.getUserId() }, null, null, " "
						+ FIELD_TIME + " desc");
		cur.moveToFirst();
		if (cur.getCount() <= 0 || cur.isLast()) {
			return null;
		}
		String userId = cur.getString(cur.getColumnIndex(FIELD_USER_ID));
		String fromID = cur.getString(cur.getColumnIndex(FIELD_FROM_ID));
		String toID = cur.getString(cur.getColumnIndex(FIELD_TO_ID));
		String sysMessage = cur.getString(cur
				.getColumnIndex(FIELD_SYSTEM_MESSAGE));
		boolean isNew = cur.getString(cur.getColumnIndex(FIELD_IS_NEW)) != null;
		SystemMessage message = new SystemMessage(userId, fromID, toID,
				sysMessage, isNew);
		cur.close();
		db.close();
		return message;
	}

	public boolean checkExist(SystemMessage message) {
		SQLiteDatabase db = this.getmDataBaseOpenHelper().getReadableDatabase();
		;
		Cursor cur = db.query(TABLE_NAME, null, FIELD_USER_ID + "=? AND "+FIELD_FROM_ID+"=?",
				new String[] { message.getUserId(),message.getFromID() }, null, null, " "
						+ FIELD_ID + " desc");
		cur.moveToFirst();
		if (cur.getCount() <= 0) {
			cur.close();
			return !true;
		}
		cur.close();
		return true;
	}
}
